#!/bin/sh

#
#   prerequisite:
#       # yum install rpm-build rpmdevtools libchewing-devel
#       $ rpmdev-setuptree
#
#   build:
#       $ cd <src>/
#       $ ./distro/fedora/gen-rpm
#
#   files located at ~/rpmbuild/{,S}RPMS
#
#   install:
#       # rpm -ivh hime-[0gq]*
#       $ imsettings-switch hime
#   

[ ! -e distro/fedora ] && exec echo Please execute '"[1m[32mdistro/fedora/gen-rpm[0m"' under hime directory, thanks.

VERSION_FILE=ChangeLog
SPEC_FILE=hime-fedora.spec
DISTRODIR=distro/fedora
DISTROROOT=`basename ${DISTRODIR}`
SRCDIR=`rpm --eval "%{_sourcedir}"`
SPECDIR=`rpm --eval "%{_specdir}"`
GIT_DIR_NAME="${PWD##*/}"

rm -fr ${DISTROROOT}
cp -r ${DISTRODIR} ${DISTROROOT}
echo "building ${SPEC_FILE} ..."
if [ -d '.git' ] ; then
    VERSION=`head -n 1 ${VERSION_FILE}`+`date +git%Y%m%d`
    TAR_NAME=hime-${VERSION}
    git archive --format=tar --prefix=${TAR_NAME}/ HEAD | xz > ${SRCDIR}/${TAR_NAME}.tar.xz
else
    VERSION=`head -n 1 ${VERSION_FILE}`
    XZ_OPT=${XZ_OPT-"-5e"}
    TAR_NAME=hime-${VERSION}
    cd ..
    cp -r $GIT_DIR_NAME $TAR_NAME
    tar --owner=0 --group=0 -Jcf "$TAR_NAME".tar.xz $TAR_NAME --exclude=.git
    cp ${TAR_NAME}.tar.xz ${SRCDIR}/${TAR_NAME}.tar.xz
    cd ${GIT_DIR_NAME}
fi

cd ${DISTROROOT}
[ -f ${SPEC_FILE} ] && rm -f ${SPEC_FILE}
sed -e "s/__hime_version__/${VERSION}/" < "${SPEC_FILE}.in" > ${SPEC_FILE}
cp -f ${SPEC_FILE} ${SPECDIR}/${SPEC_FILE}
cp -f hime.conf ${SRCDIR}
rpmbuild -ba ${SPEC_FILE}
